package logic

import (
	"api/pkg"
	"context"
	"goods_srv/goods"
	"order_srv/order"

	"api/internal/svc"
	"api/internal/types"

	"github.com/zeromicro/go-zero/core/logx"
)

type CreateOrderLogic struct {
	logx.Logger
	ctx    context.Context
	svcCtx *svc.ServiceContext
}

func NewCreateOrderLogic(ctx context.Context, svcCtx *svc.ServiceContext) *CreateOrderLogic {
	return &CreateOrderLogic{
		Logger: logx.WithContext(ctx),
		ctx:    ctx,
		svcCtx: svcCtx,
	}
}

func (l *CreateOrderLogic) CreateOrder(req *types.CreateOrderRequest) (resp *types.RegMsgResponse, err error) {
	// todo: 新增订单

	//模拟登录
	userId := 1

	//查询商品是否存在
	detail, err := l.svcCtx.GoodsSrv.GoodsDetail(l.ctx, &goods.GoodsDetailRequest{GoodsId: req.GoodsID})
	if err != nil {
		return &types.RegMsgResponse{
			Cre:  -1,
			Msg:  "服务器错误",
			Data: nil,
		}, err
	}

	if detail.GoodsId == 0 {
		return &types.RegMsgResponse{
			Cre:  -2,
			Msg:  "商品不存在",
			Data: nil,
		}, err
	}

	//获取库存
	stock, err := l.svcCtx.GoodsSrv.GetGoodsStock(l.ctx, &goods.GetGoodsStockRequest{GoodsId: req.GoodsID})
	if stock.GoodsStock < req.Num {
		return &types.RegMsgResponse{
			Cre:  -3,
			Msg:  "商品库存不足",
			Data: nil,
		}, err
	}
	//调用订单号生成
	sn := pkg.CreateGoodsSn()

	//计算总金额
	sum := detail.GoodsPrice * float32(req.Num)

	//新增订单
	createOrder, err := l.svcCtx.OrderSrv.CreateOrder(l.ctx, &order.CreateOrderRequest{
		UserId:  int64(userId),
		GoodsSn: sn,
		Amount:  sum,
		Payment: 1,
		Status:  1,
	})
	if err != nil {
		return &types.RegMsgResponse{
			Cre:  -2,
			Msg:  "服务器错误",
			Data: nil,
		}, err
	}
	//扣减库存
	_, err = l.svcCtx.GoodsSrv.DelGoodsStock(l.ctx, &goods.DelGoodsStockRequest{
		GoodsId: req.GoodsID,
		Num:     req.Num,
	})

	if err != nil {
		return &types.RegMsgResponse{
			Cre:  -3,
			Msg:  "扣减失败进行回滚",
			Data: nil,
		}, err
	}

	return &types.RegMsgResponse{
		Cre: 0,
		Msg: "订单创建成功",
		Data: map[string]interface{}{
			"orderId": createOrder.OrderId,
		},
	}, err
}
